package com.heima.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/28
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户的搜索关键词    异步调用不能从ThreadLocal中获取用户信息，所以需要传参
        Criteria criteria = Criteria.where("userId").is(userId).and("keyword").is(keyword);
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(criteria), ApUserSearch.class);
        //2.存在 更新创建时间
        if (ObjectUtil.isNotEmpty(userSearch)) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        //3.不存在，判断当前历史记录总数量是否超过10
        userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        if(CollUtil.isEmpty(apUserSearches) || apUserSearches.size() < 10){
            //小于10条，直接保存数据
            mongoTemplate.save(userSearch);
        }else {
            //不小于10条，替换最后一条数据
            ApUserSearch lastUserSearch = apUserSearches.get(apUserSearches.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),userSearch);
        }
    }

    /**
     * 删除搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        ApUser apUser = AppThreadLocalUtil.getApUser();
        if (ObjectUtil.isEmpty(dto) || ObjectUtil.isEmpty(apUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Criteria criteria = Criteria.where("userId").is(apUser.getId()).and("id").is(dto.getId());
        mongoTemplate.remove(Query.query(criteria), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获取当前用户
        ApUser apUser = AppThreadLocalUtil.getApUser();
        if(ObjectUtil.isEmpty(apUser)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Criteria criteria = Criteria.where("userId").is(apUser.getId());
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("createdTime")));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }
}
